<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="成员姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入成员姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select
          v-model="queryParams.gender"
          placeholder="请选择性别"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_USER_SEX)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthDate">
        <el-date-picker
          v-model="queryParams.birthDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="逝世日期" prop="deathDate">
        <el-date-picker
          v-model="queryParams.deathDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactInfo">
        <el-input
          v-model="queryParams.contactInfo"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
   
      <!-- <el-form-item label="代数" prop="generation">
        <el-input-number
          v-model="queryParams.generation"
          placeholder="代数"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['family:members:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['family:members:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="info"
          plain
          @click="openFamilyTree"
          v-hasPermi="['family:members:query']"
        >
          <Icon icon="mdi:family-tree" class="mr-5px" /> 查看族谱
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="成员姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          {{ scope.row.gender === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column label="出生日期" align="center" prop="birthDate" width="180" />
      <el-table-column label="逝世日期" align="center" prop="deathDate" width="180" />
      <el-table-column label="联系方式" align="center" prop="contactInfo" />
      <el-table-column label="成员照片" align="center" prop="photoUrl" width="100">
        <template #default="scope">
          <el-image
            v-if="scope.row.photoUrl"
            :src="scope.row.photoUrl"
            :preview-src-list="[scope.row.photoUrl]"
            preview-teleported
            class="h-40px w-40px"
          />
          <el-avatar v-else :size="40" icon="el-icon-user" />
        </template>
      </el-table-column>
      <el-table-column label="代数" align="center" prop="generation" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="操作" align="center" min-width="120">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['family:members:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="success"
            @click="openRelationships(scope.row.id)"
            v-hasPermi="['family:relationships:query']"
          >
            关系管理
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['family:members:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MembersForm ref="formRef" @success="getList" />
  <!-- 关系管理弹窗 -->
  <el-dialog
    v-model="relationshipsVisible"
    title="关系管理"
    width="800px"
    append-to-body
    destroy-on-close
  >
    <Relationships :member-id="currentMemberId" />
  </el-dialog>
  <!-- 族谱查看弹窗 -->
  <el-dialog
    v-model="familyTreeVisible"
    title="家族族谱"
    width="90%"
    top="5vh"
    fullscreen
    append-to-body
    destroy-on-close
  >
    <FamilyTree />
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { MembersApi, MembersVO } from '@/api/family/members'
import MembersForm from './MembersForm.vue'
import Relationships from './Relationships.vue'
import FamilyTree from './FamilyTree.vue'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'

/** 家族成员 列表 */
defineOptions({ name: 'Members' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<MembersVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  gender: undefined,
  birthDate: [],
  deathDate: [],
  contactInfo: undefined,
  photoUrl: undefined,
  biography: undefined,
  generation: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 新增：用于存储族谱数据
const familyTreeData = ref(null)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MembersApi.getMembersPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MembersApi.deleteMembers(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MembersApi.exportMembers(queryParams)
    download.excel(data, '家族成员.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 查看族谱按钮操作 */
const handleViewTree = async () => {
  try {
    loading.value = true // 可以复用列表的 loading 状态
    const data = await MembersApi.getFamilyTree()
    familyTreeData.value = data // 将获取到的数据存起来
    console.log('Family Tree Data:', familyTreeData.value)
    // 这里可以添加打开新页面或弹窗来显示族谱图的逻辑
    message.success('族谱数据已加载到控制台，请查看') 
  } catch (error) {
    console.error('Failed to load family tree data:', error)
    message.error('加载族谱数据失败')
  } finally {
    loading.value = false
  }
}

/** 关系管理操作 */
const relationshipsVisible = ref(false)
const currentMemberId = ref<number>()
const openRelationships = (id: number) => {
  currentMemberId.value = id
  relationshipsVisible.value = true
}

/** 族谱查看操作 */
const familyTreeVisible = ref(false)
const openFamilyTree = () => {
  familyTreeVisible.value = true
  handleViewTree()
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>
